package com.yugu.park.system.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.PageInfo;
import com.yugu.util.BeanCopyUtil;
import com.yugu.util.DataUtils;
import com.yugu.util.SearchPage;
import com.yugu.park.system.mapper.SysUserMapper;
import com.yugu.park.enums.SequenceTypeEnum;
import com.yugu.park.system.entity.SysRoleEntity;
import com.yugu.park.system.entity.SysUserEntity;
import com.yugu.park.system.service.SysUserService;
import com.yugu.park.system.service.TSysSequenceService;
import com.github.pagehelper.PageHelper;

@Service
@Transactional
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements SysUserService {
    @Resource
	private SysUserMapper mapper;
    @Autowired
	private TSysSequenceService sequenceService;
	@Override
	public PageInfo<SysUserEntity> page(SearchPage<SysUserEntity> search) {
		PageHelper.startPage(search.getPageNum(),search.getPageSize());
        List<SysUserEntity> list = mapper.page(search.getSearch());
        return PageInfo.of(list);
	}
	@Override
	public void addOrUpdate(SysUserEntity t) {
		List<SysRoleEntity> roles = t.getRoles();
		SysUserEntity old = mapper.selectById(t.getUserId());
		if(old!=null) {
			//修改
			if(roles!=null&&roles.size()>0) {
				mapper.deleteUserAndRoleByUserId(t.getUserId());
			}
			BeanCopyUtil.copyProperties(t,old);
			mapper.updateById(old);
		}else {
			long next = sequenceService.getNextNoTime(SequenceTypeEnum.EMPLOYEE);
			String loginName = DataUtils.getEmpNO("U", next);
			t.setUserName(loginName);
			//新增
			t.setPassword(new BCryptPasswordEncoder().encode(t.getPassword()));
			t.setUserId(UUID.randomUUID().toString().replaceAll("-", ""));
			mapper.insert(t);
		}
		if(roles!=null&&roles.size()>0) {
			mapper.batchUserAndRole(t,roles);
		}
	}

}
